import {
  shops,
  shopList
} from '~/tools/shops'
import {
  dsx
} from '~/tools/datax'
import {
  msg
} from '~/tools/msg'
export const orderTool = {
  totalGoodsNum(order) {
    return order.goodsList.reduce((sum, goods) => {
      return sum + goods.num * 1
    }, 0)
  },
  changeDeliveryShop({
    order,
    orderAddr,
    shopId,
    cb
  }) {
    const oldShopId = `${orderAddr.shop}`
    orderAddr.shop = `${shopId}`
    order.shop = shops.getShop(shopId)
    const addrList = orderAddr?.list || [orderAddr]
    addrList.forEach(ele => {
      if (`${ele.shop}` == oldShopId) ele.shop = `${shopId}`
    })
    // console.log(orderAddr)
    dsx.cloudUpdate('delivery_addr', orderAddr._id, orderAddr)
      .then(async res => {
        const success = res.result.errMsg.endsWith(":ok")
        if (cb) cb(success, res)
      }).catch(err => {
        if (cb) cb(false, res)
        console.error(err)
      })
  },
  changeOrderStatus({
    orderId,
    data
  }) {
    return dsx.cloudUpdate('orders', orderId, data)
  },
  async startDelivery(order, cancel = false, deliveryMan) {
    // deliveryMan = {_openid, _id}
    const orderId = order.id || order._id
    const user = deliveryMan || this.data.user
    // console.log(user._openid, orderId, cancel)
    let result = null
    await wx.cloud.callFunction({
        name: 'startDelivery',
        data: {
          deliveryMan: user._openid,
          orderId,
          cancel
        }
      })
      .then(async res => {
        result = res
        if (deliveryMan) await msg.notifyDeliveryMan(order._id, deliveryMan._id)
      })
    return result
  },
}